//
//  PublishMimiController.m
//  Qzone
//
//  Created by zhangxy on 2018/7/19.
//  Copyright © 2018年 zhang. All rights reserved.
//

#import "PublishMimiController.h"

#import "ZTextView.h"
#import "ChooseTypeController.h"
#import "ChooseLabelController.h"
#import "NavTypeEntity.h"

#import "MyButton.h"
#import "XHImageViewer.h"

#import "RITLPhotos.h"

#import "UIView+Border.h"

@interface PublishMimiController ()<ImagePickerDelegate,UITextViewDelegate,RITLPhotosViewControllerDelegate>{
    UIButton *curBtn;
    
    NavTypeEntity *checkType;
}

@property(nonatomic,strong) UIView *conentView;
@property(nonatomic,strong) ZTextView *titleView;
@property(nonatomic,strong) ZTextView *textView;

@property(nonatomic,strong) UIScrollView *mainScroll;
@property(nonatomic,strong) UIView *menuScroll;

@property(nonatomic,strong) UIButton *btnMimi;

@property(nonatomic,strong) NSMutableArray *labels;

@end

@implementation PublishMimiController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"";
    [self setNavigationBar];
    
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0,0,56,26)];
    [button setBackgroundColor:UIColorFromRGBAlpha(TextWhiteColor, 0.3)];
    [button setTitle:@"发布" forState:0];
    [button.titleLabel setFont:FontFiftent];
    button.layer.cornerRadius = 8.0f;
    button.layer.masksToBounds = YES;
    [button addTarget:self action:@selector(publishAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *btn = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.rightBarButtonItem = btn;
    self.navigationController.navigationBarHidden = NO;
    
    _labels = [[NSMutableArray alloc] init];
    
    
    [self createViewByType];
    
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(allHideKeyBoard)];
    self.view.userInteractionEnabled = YES;
    [self.view addGestureRecognizer:tap];
}

-(void)publishAction{
    // 发布
    if(_labels.count == 0){
        [PopUtil showMessage:@"请选项标签" positionType:PopPositionTypeMiddle];
        return;
    }
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    NSString *strTag = @"";
    for (NavTypeEntity *tagItem in _labels) {
        strTag = [strTag stringByAppendingFormat:@"%@,",tagItem.tag_id];
    }
    if(strTag.length>0){
        strTag = [strTag substringToIndex:strTag.length - 1];
    }
    
    
    [NetworkUtil POST:API_publishImage(@"mimi")
           parameters:@{@"session_uid":[UserUtil getUser].user_id,
                              @"title":convertToString(_titleView.text),
                            @"message":convertToString(_textView.text),
                             @"tag_id": strTag,
                             @"is_public":convertIntToString(!_btnMimi.selected)
                             } success:^(id responseObject, NSDictionary *dict) {
                                 [MBProgressHUD hideHUDForView:self.view animated:YES];
                                 [PopUtil showMessage:dict[@"msg"]];
                                 [self backAction];
                             } failure:^(NSError *error, NSString *message) {
                                 [MBProgressHUD hideHUDForView:self.view animated:YES];
                                 [PopUtil showMessage:message];
                                 
                             }];
}

-(void)createViewByType{
    UIImageView *bgView = [self createImageView];
        [bgView setBackgroundColor:UIColorFromRGB(PublishBgColor)];
        [bgView setFrame:CGRectMake(0, 0, ScreenWidth, 44)];
        [self.view addSubview:bgView];
        
        UILabel *lab = [self createLabel];
        
        [lab setFrame:CGRectMake(20, 0, ScreenWidth - 40, 44)];
        [lab setFont:FontFiftent];
        [lab setTextColor:UIColorFromRGB(TextSizeEightColor)];
        [lab setBackgroundColor:UIColor.clearColor];
        [lab setFont:FontThirteen];
        [lab setText:@"除了你自己，没有人会知道你的身份"];
        [self.view addSubview:lab];
   
    _conentView = [[UIView alloc] initWithFrame:CGRectMake(15, 44+10, ScreenWidth-30, 138)];
    _titleView = [self createTextView];
    [_titleView setFrame:CGRectMake(0, 10, ScreenWidth - 30, 40)];
    [_titleView addBottomBorderWithColor:UIColorFromRGB(BgLineColor) andWidth:1.0f];
    [self.titleView setPlaceholder:@"说个秘密吧..."];
    
    _textView = [self createTextView];
    [_textView setFrame:CGRectMake(0, 64, ScreenWidth - 30, 64)];
    [_textView addBottomBorderWithColor:UIColorFromRGB(BgLineColor) andWidth:1.0f];
    [self.textView setPlaceholder:@"我的小秘密"];
    
    [_conentView addSubview:_titleView];
    [_conentView addSubview:_textView];
    [self.view addSubview:_conentView];
    
    _menuScroll = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_conentView.frame)+10, ScreenWidth, 108)];
    [_menuScroll setBackgroundColor:[UIColor clearColor]];
    [self.view addSubview:_menuScroll];
    
    
    
        UIButton *btn2 = [self createButton];
        btn2.layer.cornerRadius = 8.0f;
        btn2.layer.masksToBounds = YES;
        btn2.layer.borderWidth = 1.0f;
        [btn2 setTitle:@"添加标签" forState:0];
        [btn2 setTitleColor:UIColorFromRGB(TextLinkColor) forState:0];
        btn2.layer.borderColor = UIColorFromRGB(BgListSectionColor).CGColor;
        [btn2 setFrame:CGRectMake(118, 0, 88, 30)];
        btn2.tag = 2;
        [btn2 addTarget:self action:@selector(tagClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.menuScroll addSubview:btn2];
    
        [btn2 setFrame:CGRectMake(20, 0, 88, 30)];
    
        _btnMimi = [self createButton];
        _btnMimi.layer.cornerRadius = 8.0f;
        _btnMimi.layer.masksToBounds = YES;
        _btnMimi.layer.borderWidth = 1.0f;
        _btnMimi.layer.borderColor = UIColorFromRGB(BgTitleColor).CGColor;
        [_btnMimi setFrame:CGRectMake(118, 0, 88, 30)];
        [_btnMimi setTitle:@"公开" forState:0];
        _btnMimi.tag = 4;
        [_btnMimi setTitleColor:UIColorFromRGB(BgTitleColor) forState:0];
        [_btnMimi addTarget:self action:@selector(tagClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.menuScroll addSubview:_btnMimi];
}


- (ZTextView *)createTextView
{
    ZTextView  *textView = [[ZTextView alloc] init];
    textView.frame = CGRectMake(15,64,SCREEN_WIDTH - 30, 140);
    //        _textView.textContainerInset = UIEdgeInsetsMake(5, 5, 5, 5);
    textView.placeholder = self.navigationItem.title;
    textView.placeholderColor = LIGHT_GRAY_COLOR;
    textView.textColor = UIColorFromRGB(TextSizeEightColor);
    textView.delegate = self;
    textView.font = FontFiftent;
    //        _textView.inputAccessoryView = self.keyboardView;
    textView.showsVerticalScrollIndicator = NO;
//    [textView becomeFirstResponder];  //弹出键盘
    return textView;
}



-(void)tagClick:(UIButton *)btn{
    // tag = 1,分类，2标签，3话题，4公开/不公开
    if(btn.tag == 4){
        if(_btnMimi.selected){
            [_btnMimi setTitle:@"公开" forState:0];
            _btnMimi.selected = NO;
        }else{
            [_btnMimi setTitle:@"不公开" forState:0];
            _btnMimi.selected = YES;
        }
        return;
    }
    ChooseLabelController *vc = [[ChooseLabelController alloc] init];
    vc.type = (int)btn.tag;
    vc.entity = checkType;
    [vc setZZChooseResultBlock:^(id tagObj) {
        NavTypeEntity *typeItem = tagObj;
        BOOL isHad = NO;
        for (NavTypeEntity *item in _labels) {
            if([typeItem.tag_id isEqual:item.tag_id]){
                isHad = YES;
                break;
            }
        }
        
        if(!isHad){
            [_labels addObject:tagObj];
            [self reSetButtonLocation];
        }
        
    }];
    [self openPushVC:vc];
}


-(void)backAction{
    [self.navigationController popViewControllerAnimated:YES];
}


-(void)reSetButtonLocation{
    // 获取标签的控件
    UIButton *btnLabel = [_menuScroll viewWithTag:2];
    
    // 是否公开按钮
    UIButton *btnSecret = [_menuScroll viewWithTag:4];
    
    for (MyButton *btn in _menuScroll.subviews) {
        if(btn.tag >= 100){
            [btn removeFromSuperview];
        }
    }
    
    CGRect sf = CGRectMake(20, 0, 88, 30);
    
    CGFloat x = sf.origin.x;
    CGFloat y = sf.origin.y;
    
    for (int i = 0; i<_labels.count; i++) {
        NavTypeEntity *entity = [_labels objectAtIndex:i];
        MyButton *btn = [MyButton buttonWithType:UIButtonTypeCustom];
        [btn.titleLabel setFont:FontFiftent];
        [btn setTitleColor:UIColorFromRGB(TextSizeEightColor) forState:0];
        btn.layer.cornerRadius = 8.0f;
        btn.layer.masksToBounds = YES;
        btn.layer.borderWidth = 1.0f;
        btn.layer.borderColor = UIColorFromRGB(BgListSectionColor).CGColor;
        btn.objTag = entity;
        btn.tag = 100+i;
        [btn setTitle:[NSString stringWithFormat:@"%@ x",entity.tag_name] forState:0];
        [btn addTarget:self action:@selector(closeTagButton:) forControlEvents:UIControlEventTouchUpInside];
        
        CGSize s = [self autoWidthOfLabel:btn.titleLabel with:sf.size.height];
        if(ScreenWidth - x - s.width > 30){
            [btn setFrame:CGRectMake(x, y, s.width+10, sf.size.height)];
        }else{
            y = y + 40;
            x = 20;
            [btn setFrame:CGRectMake(x, y, s.width+10, sf.size.height)];
        }
        x = x + s.width + 20;
        
        [_menuScroll addSubview:btn];
    }
    
    if(ScreenWidth - x - 88 < 10){
        y = y + 40;
        x = 20;
    }
    [btnLabel setFrame:CGRectMake(x, y, 88, 30)];
    x = x + 88 + 10;
    
    if(btnSecret){
        if(ScreenWidth - x - 88 > 10){
            [btnSecret setFrame:CGRectMake(x, y, 88, 30)];
        }else{
            y = y + 40;
            x = 20;
            [btnSecret setFrame:CGRectMake(x, y, 88, 30)];
        }
    }
}

-(void)closeTagButton:(MyButton *) btn{
    NavTypeEntity *obj = btn.objTag;
    [_labels removeObject:obj];
    [self reSetButtonLocation];
}



#pragma mark - textview delegate
- (void)textViewDidChange:(UITextView *)textView
{
    if (textView.markedTextRange == nil) {
        textView.attributedText = [textView.text formatWithParagraph:5.0 fontSize:15 textColor:[UIColor blackColor]];
    }
}



-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self allHideKeyBoard];
}

- (void)allHideKeyBoard
{
    for (UIWindow* window in [UIApplication sharedApplication].windows)
    {
        for (UIView* view in window.subviews)
        {
            [self dismissAllKeyBoardInView:view];
        }
    }
}

-(BOOL) dismissAllKeyBoardInView:(UIView *)view
{
    if([view isFirstResponder])
    {
        [view resignFirstResponder];
        return YES;
    }
    for(UIView *subView in view.subviews)
    {
        if([self dismissAllKeyBoardInView:subView])
        {
            return YES;
        }
    }
    return NO;
}

// 隐藏键盘
-(void)downKeyBoard:(id)sender{
    [self allHideKeyBoard];
}
-(BOOL)gestureRecognizer:(UIGestureRecognizer*)gestureRecognizer shouldReceiveTouch:(UITouch*)touch {
    
    if ([touch.view isKindOfClass:[UIScrollView class]]) {
        
        return YES;
        
    }
    
    return NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/**
 计算Label高度
 
 @param label 要计算的label，设置了值
 @param width label的最大宽度
 */
- (CGSize )autoWidthOfLabel:(UILabel *)label with:(CGFloat )height{
    //Calculate the expected size based on the font and linebreak mode of your label
    // FLT_MAX here simply means no constraint in height
    CGSize maximumLabelSize = CGSizeMake(FLT_MAX, height);
    
    CGSize expectedLabelSize = [label sizeThatFits:maximumLabelSize];
    
    //adjust the label the the new height.
    CGRect newFrame = label.frame;
    newFrame.size.width = expectedLabelSize.width;
    label.frame = newFrame;
    [label updateConstraintsIfNeeded];
    
    return expectedLabelSize;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
